module repository.dept;

import database.mydb;
import models.dept;

/** 
 * 获取部门
 * Returns: Dept[]
 */
Dept[] getAllDepts()
{
    return dbsess.createQuery("FROM Dept ORDER BY id").list!Dept();
}

/** 
 * 根据获取部门
 * Returns: Dept
 */
Dept getDeptById(long deptId)
{
    Dept dept = dbsess.createQuery("FROM Dept WHERE id=:deptId")
        .setParameter("deptId", deptId).uniqueResult!Dept();

    return dept;
}

/** 
 * 添加部门
 * Params:
 *   newDept = Dept
 * Returns: bool
 */
bool doAddDept(Dept newDept)
{
    auto res = dbsess.save(newDept);
    if (!res.hasValue || res <= 0)
    {
        return false;
    }
    return true;
}

/** 
 * 删除部门
 * Params:
 *   deptId = long
 * Returns: bool
 */
bool deleteDeptById(long deptId)
{
    Dept dept = dbsess.createQuery("FROM Dept WHERE id=:deptId")
        .setParameter("deptId", deptId).uniqueResult!Dept();

    if (dept is null)
    {
        return false;
    }
    dbsess.remove(dept);

    // 删除子部门
    auto subDeptList = dbsess.createQuery("FROM Dept WHERE parentId=:parentId")
        .setParameter("parentId", deptId).list!Dept();
    foreach (subDept; subDeptList)
    {
        dbsess.remove(subDept);
    }
    return true;
}

/** 
 * 批量删除
 * Params:
 *   deptIds = long[]
 * Returns: bool
 */
bool deleteDeptByIds(long[] deptIds)
{
    foreach (did; deptIds)
    {
        Dept dept = dbsess.createQuery("FROM Dept WHERE id=:deptId")
            .setParameter("deptId", did).uniqueResult!Dept();

        if (dept is null)
        {
            continue;
        }
        dbsess.remove(dept);
    }

    return true;
}

/** 
 * 修改部门
 * Params:
 *   newDept = Dept
 * Returns: bool
 */
bool doUpdateDept(long deptId, Dept newDept)
{
    Dept oldDept = dbsess.createQuery("FROM Dept WHERE id=:deptId")
        .setParameter("deptId", deptId).uniqueResult!Dept();
    if (oldDept is null)
    {
        return false;
    }
    oldDept.parentId = newDept.parentId;
    oldDept.name = newDept.name;
    oldDept.sort = newDept.sort;
    oldDept.status = newDept.status;

    dbsess.update(oldDept);
    return true;
}
